package aad.storyboard.model;

import java.io.FileNotFoundException;
import java.util.HashMap;

import android.content.res.Resources;

public class ImageProvider{
	
	public HashMap<Integer, Image> prototypes;
	private static ImageProvider instance = new ImageProvider();
	private Resources resources;
	private ImageFactory imgFactory;
	
	static{
		try
		{
			Class.forName("aad.storyboard.model.SVGImage");
			Class.forName("aad.storyboard.model.BitmapImage");
		}
		catch (ClassNotFoundException any)
		{
			any.printStackTrace();
		}
	}
	public static ImageProvider getInstance(Resources res){
		instance.resources = res;
		return ImageProvider.instance;
	}
	private ImageProvider(){
		imgFactory = ImageFactory.getInstance();
		prototypes = new HashMap<Integer,Image>();
	}
	
	public Image getImage(int id) throws Exception{
		Integer key = new Integer(id);
		Image toClone = null;
		if(!prototypes.containsKey(key)){
				toClone = this.provideNewImage(id);
				prototypes.put(key, toClone);
		}
		else {
			toClone = prototypes.get(key);
		}
		Image copy = (Image) toClone.clone();
		return copy;
		
	}
	
	private Image provideNewImage(int id) throws FileNotFoundException {
		int type = this.determineImageType(id);
		Image img = this.imgFactory.createImage(this.resources, id);
		return img;
	}
	
	private int determineImageType(int id) {
		String resource = this.resources.getResourceName(id);
		if(resource.endsWith("jpg") || resource.endsWith(".png"))
			return Image.TYPE_BITMAP;
		else if (resource.endsWith("svg"))
			return Image.TYPE_VECTOR;
		return -1;
	}

}
